package com.ipan.jfinal.json;

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jfinal.json.IJsonFactory;
import com.jfinal.json.Json;
import com.jfinal.plugin.activerecord.Record;

/**
 * 自定义JsonFactory
 * 对Date类型不统一使用具体格式，而是交给FastJson的注解来控制！
 * 对其他对象的Date类型统一处理；
 * 
 * 配置初始化，configConstant(Constants me)中me.setJsonFactory(MyFastJsonFactory.me());
 * 这样可以自定义JsonKit和控制器的renderJson；
 * 
 * @author iPan
 * @version 2019-01-10
 */
public class MyFastJsonFactory implements IJsonFactory {
	
	private static final MyFastJsonFactory me = new MyFastJsonFactory();
	private static SerializerFeature[] DEFAULT_SERIALIZER_FEATURE = null;
	
	public static MyFastJsonFactory me() {
		return me;
	}
	
	public static void setDefaultSerializerFeature(SerializerFeature[] defaultSerializerFeature) {
		DEFAULT_SERIALIZER_FEATURE = defaultSerializerFeature;
	}
	
	public static void initNullMapper() {
		initNullMapper(true);
	}
	public static void initNullMapper(boolean disableCircularReference) { // 让返回的json字符串支持null值
		DEFAULT_SERIALIZER_FEATURE = (disableCircularReference) 
				? new SerializerFeature[] {
					SerializerFeature.DisableCircularReferenceDetect,
					SerializerFeature.WriteMapNullValue,
					SerializerFeature.WriteNullNumberAsZero,
					SerializerFeature.WriteNullListAsEmpty,
					SerializerFeature.WriteNullStringAsEmpty,
					SerializerFeature.WriteNullBooleanAsFalse,
					SerializerFeature.WriteDateUseDateFormat // 默认是yyyy-MM-dd HH:mm:ss，可以使用JSONField去覆盖；
				} 
				: new SerializerFeature[] {
					SerializerFeature.WriteMapNullValue,
					SerializerFeature.WriteNullNumberAsZero,
					SerializerFeature.WriteNullListAsEmpty,
					SerializerFeature.WriteNullStringAsEmpty,
					SerializerFeature.WriteNullBooleanAsFalse,
					SerializerFeature.WriteDateUseDateFormat
				};
	}
	
	public Json getJson() {
		return new MyFastJson(DEFAULT_SERIALIZER_FEATURE);
	}
	
	/**
	 * 移除 FastJsonRecordSerializer
	 * 仅为了与 jfinal 3.3 版本之前版本的行为保持一致
	 */
	public void removeRecordSerializer() {
		SerializeConfig.getGlobalInstance().put(Record.class, null);
	}
	
}